package in.iqing.model.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import in.iqing.control.helper.LogHelper;


/**
 * Created by Zuoshu on 2014/11/4.
 */
public class UniqueList<E> extends ArrayList<E> {

    private Set<Integer> keySet = new HashSet<Integer>();

    @Override
    public boolean add(E e) {
        if (e == null) {
            return super.add(e);
        }
        int hashCode = e.hashCode();
        if (keySet.contains(hashCode)) {
            LogHelper.warn("UniqueList", "duplicate hashCode:" + hashCode + " e:" + e.toString());
            return false;
        } else {
            keySet.add(hashCode);
            return super.add(e);
        }
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        if (c == null || c.size() == 0) {
            return super.addAll(c);
        }

        boolean result = false;
        for (E e : c) {
            result |= add(e);
        }
        return result;
    }

    @Override
    public void clear() {
        keySet.clear();
        super.clear();
    }
}
